<?php

namespace app\common\library\device\cabinet;

use addons\mycurrency\library\Common;
use app\common\library\queuemqtt\QueueMqttPublisher;
use app\common\model\mycurrency\Device;
use app\common\model\mycurrency\DeviceInstruction;
use app\common\mqtt\MqttPublisher;
use BugHonorFileTimeTest\BugHonorFileTimeTest;
use GatewayWorker\Lib\Gateway;
use think\Hook;
use think\Queue;

/**
 * 控制指令
 */
class Control
{

    /**
     * 下发控制指令
     * @param int $device_id 设备id
     * @param int $code 通讯指令
     * @param array $data 发送数据
     * @param array $instruction_extend 日志表扩展数据
     */
    public static function sending($device_id,$code,$data = [],$instruction_extend = []){
        //组装要发送的数据
        $message = Analysis::sendingAssemble($code,$device_id,$data);

        //发送地址
        $serial_number = Device::where(['id' => $device_id])->value('serial_number');
        $topic = "ZHZN/{$serial_number}";


        $queue_default = config('queue.default');
        $job = "app\common\job\MqttRepublish@republish";
        $jobData = [
            'topic' => $topic,
            'data' => $message
        ];

//        $mqtt = new QueueMqttPublisher();
//        $mqtt->publishMessage($jobData['topic'], $jobData['data']);
        Queue::later(1, $job, $jobData, $queue_default);

        //发送数据
        //$serial_number = Device::where(['id' => $device_id])->value('serial_number');
        //$mqtt_publisher = new MqttPublisher();
        //$mqtt_publisher->publishMessage($serial_number,$message);

        //记录发送日志
        $instruction_id = DeviceInstruction::increase($device_id,$code,json_encode($message),$message['mi'],$instruction_extend);

        //更新message_id
        Analysis::messageidUpdate($device_id,$message['mi']);
        return $instruction_id;
    }
}
